#!/usr/bin/perl
use IO::Handle;
use DBI;
$serverip="192.168.1.100";
$db_hostname="192.168.1.100";
$db_port="3306";
$dsn="DBI:mysql:database=mumonitor;host=$db_hostname;port=$db_port";
$dbuser="mudba";
$dbpasswd="mudba";
$dbh = DBI->connect($dsn,$dbuser,$dbpasswd);
$delsql="delete from mu_sshmessage where serverip='$serverip'";
$dbh->do("$delsql");

$naptime = 30;
chomp ($hostname = `/bin/hostname`);
open SECURESSH, "/var/log/secure" or die "can't open /var/log/secure: $!";
for (;;) {
        chomp($curr_user=`/usr/bin/w -sh|/usr/bin/wc -l`);
        $updatesql = "update mu_server SET currentuser='$curr_user' where serverip='$serverip'";
        $dbh = DBI->connect($dsn,$dbuser,$dbpasswd);
        $dbh->do("$updatesql");

        $uptime_tmp = `uptime`;
        $uptime_tmp =~ m/(.*) up (.*),  \d* user(.*)/;
        $uptime = $2;
        $uptime_sql = "update mu_server SET uptime = '$uptime' where serverip='$serverip'";
        $dbh->do("$uptime_sql");

        while (<SECURESSH>) {
        if (m/^(.*) $hostname sshd\[\d*\]: Accepted password for (.*) from (.*) port .*/){
                        chomp ($logdate = `/bin/date -d "$1" "+%Y-%m-%d %T"`);
                        $username = $2;
                        $ipaddr = $3;
                        $typeid = 1;
                        $sql = "insert into mu_sshmessage values('$serverip','$username','$ipaddr','$logdate','$typeid')";
                        $dbh->do("$sql");
        } elsif (m/^(.*) $hostname sshd\[\d*\]: Invalid user (.*) from (.*)/) {
                        chomp ($logdate = `/bin/date -d "$1" "+%Y-%m-%d %T"`);
                        $username = $2;
                        $ipaddr = $3;
                        $typeid = 0;
                        $sql = "insert into mu_sshmessage values('$serverip','$username','$ipaddr','$logdate','$typeid')";
                        $dbh->do("$sql");
        } elsif (m/^(.*) $hostname sshd\[\d*\]: Failed password for (.*) from (.*) port .*/) {
                        chomp ($logdate = `/bin/date -d "$1" "+%Y-%m-%d %T"`);
                        $username = $2;
                        $ipaddr = $3;
                        $typeid = 0;
                        $sql = "insert into mu_sshmessage values('$serverip','$username','$ipaddr','$logdate','$typeid')";
                        $dbh->do("$sql");
        } elsif (m/^(.*) $hostname sshd\[\d*\]: Accepted publickey for (.*) from (.*) port .*/) {
			chomp ($logdate = `/bin/date -d "$1" "+%Y-%m-%d %T"`);
                        $username = $2;
                        $ipaddr = $3;
                        $typeid = 1;
                        $sql = "insert into mu_sshmessage values('$serverip','$username','$ipaddr','$logdate','$typeid')";
                        $dbh->do("$sql");
    }
        }
        sleep $naptime;
        SECURESSH->clearerr();  #clear stdio error flag
}
$dbh->disconnect();
